<?php
/**
 * @Author:      lyt
 * @DateTime:    2016-01-05 10:18:43
 * @Description: Description
 */
class ScsSearchController extends BaseController {
   /**
     * @Author:      lyt
     * @DateTime:    2016-01-04 16:38:37
     * @Description: 获取信息
     */
   /**
    * @Author:      lyt
    * @DateTime:  2017-03-25 10:12:22
    * @Description: 修改 代码 添加  对于洗车单的支持  不足的位置补空 或0  订单类型为 3
    */
    public  function search_order(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                "page"=>'integer',
                "page_size"=>'integer',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $page_size=Input::get("page_size",10);
            $page=Input::get("page",1);
            // $orders=Orders::where("shop_id",$sc_user->shop_id)->whereIn('status',Orders::$search_order)->orderBy("book_time",'desc');
            // if(Input::get("order_id")){
            //     $orders=$orders->where("order_id","like","%".Input::get("order_id")."%");
            // }
            // if(Input::get("car_no")){
            //     $orders=$orders->where("car_no",'like','%'.Input::get("car_no").'%');
            // }
            // if(Input::get("phone")){
            //     $orders=$orders->where("phone",'like','%'.Input::get("phone").'%');
            // }
            // if(Input::get("book_time")){
            //     $orders=$orders->where("book_time",Input::get("book_time"));
            // }
            // if(Input::get("place")){
            //     $orders=$orders->where("place",Input::get("place"));
            // }
            // if(Input::get("order_type")){
            //     $orders=$orders->where("order_type",Input::get("order_type"));
            // }
            // $count=$orders->count();
            // $orders=$orders->skip($page_size*($page-1))->take($page_size)->get();
            //添加洗车单后查询

            $sql_order="SELECT order_id,pay_time,   start_time, end_time,   book_time,book_hour,place,order_type,status,created_at,
                        car_no, phone,car_brand_id, car_brand_name,car_series_id,car_series_name,car_model_id,car_model_name,mileage,is_call,call_status
                    FROM
                        `orders`
                    WHERE   shop_id = ".$sc_user->shop_id."
                    AND `status` IN (1018,1112,1213,1214,1215,1216,1217,1219,1317,1411,1412,1416,1417,1419,1420,1117,1312)";
            $car_wash_order="SELECT order_id,pay_time,begin_time AS start_time,end_time,date_format(created_at, '%Y-%m-%d') book_time,
                        '' book_hour,2 place,3 order_type,status,created_at,car_no,phone,'' car_brand_id,'' car_brand_name,
                        '' car_series_id,'' car_series_name,'' car_model_id,'' car_model_name,0 mileage, 0 is_call, 0 call_status
                    FROM
                        car_wash_order
                    WHERE
                        shop_id = ".$sc_user->shop_id;
            if(Input::get("order_id")){
                $sql_order.=" and order_id like '%".Input::get("order_id")."%'";
                $car_wash_order.=" and order_id like '%".Input::get("order_id")."%'";
            }
            if(Input::get("car_no")){
                $sql_order.=" and car_no like '%".Input::get("car_no")."%'";
                $car_wash_order.=" and car_no like '%".Input::get("car_no")."%'";
            }
            if(Input::get("phone")){
                $sql_order.=" and phone like '%".Input::get("phone")."%'";
                $car_wash_order.=" and phone like '%".Input::get("phone")."%'";
            }
            if(Input::get("book_time")){
                $sql_order.=" and book_time ='".Input::get("book_time")."'";
                $car_wash_order.=" and date_format(created_at, '%Y-%m-%d') ='".Input::get("book_time")."'";
            }
            if(Input::get("place")){
                // $orders=$orders->where("place",Input::get("place"));
                $sql_order.=" and place =".Input::get("place");
                $car_wash_order.=" and 2 =".Input::get("place");
            }
            if(Input::get("order_type")){
                $sql_order.=" and order_type =".Input::get("order_type");
                $car_wash_order.=" and 3 =".Input::get("order_type");
            }
            $get_status = preg_replace('/\[|\]/', '',Input::get("status"));
            if(!empty($get_status)){
                $sql_order.=" and status in ($get_status) ";
                $car_wash_order.=" and status in ($get_status) ";
            }
            $sql="SELECT  * FROM  (
                    ".$sql_order."
                    UNION ALL
                    ".$car_wash_order."
                ) AS temp ";

            $limitsql= ' limit '.$page_size*($page-1).','.$page_size;
            $count=DB::select("select count(1) count from( ".$sql.") as count");
            $sql=$sql." order by book_time desc ";

            $orders=DB::select($sql.$limitsql);
            $arr_order=array();
            foreach ($orders as $_order) {
                $arr_order[]=array(
                    "order_id"=>$_order->order_id,
                    "pay_time"=>$_order->pay_time,
                    "start_time"=>$_order->start_time,
                    "end_time"=>$_order->end_time,
                    "book_time"=>$_order->book_time,
                    "book_hour"=>$_order->book_hour,
                    "place"=>$_order->place,
                    "order_type"=>$_order->order_type,
                    "status"=>$_order->status,
                    "created_at"=>$_order->created_at,
                    "car_no"=>$_order->car_no,
                    "phone"=>$_order->phone,
                    "brand_id"=>$_order->car_brand_id,
                    "brand_name"=>$_order->car_brand_name,
                    "series_id"=>$_order->car_series_id,
                    "series_name"=>$_order->car_series_name,
                    "model_id"=>$_order->car_model_id,
                    "model_name"=>$_order->car_model_name,
                    "mileage"=>$_order->mileage,
                    "is_call"=>$_order->is_call,
                    "call_status"=>$_order->call_status,
                );
            }
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("count"=>$count[0]->count,"orders"=>$arr_order));
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "search_order", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);

    }


     /**
     * @Author:      lyt
     * @DateTime:    2016-01-04 16:38:37
     * @Description: 获取信息
     */
    public  function search_user(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                "phone"=>'required',
                "car_no"=>'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $user=Users::where("phone",Input::get("phone"))->first();
            $user_array=null;
            $car_info=null;
            if($user){//如果存在用户判断用户
                if($user->status!=1){
                    $response = Lang::get("scs_error.order_cusuom_error_40004");
                    $response["result"]=$validator->messages()->all();
                    break;
                }else{//如果用户状态 正常
                    $user_array=array(
                        "name"=>$user->real_name,
                        "phone"=>$user->phone,
                    );
                    $car=UserCarInfo::where("user_id",$user->id)->where("car_no",Input::get("car_no"))->where("status",1)->first();
                    if($car){
                        $csi=DataCarStandardInfo::leftJoin("car_series","car_series.id","=","car_standard_info.series_name_id")->leftJoin("car_brand","car_brand.id","=","car_standard_info.brand_name_id")->select("car_standard_info.model_name","car_series.name as series_name","car_brand.name as brand_name")->where("car_standard_info.id",$car->car_model_id)->first();
                        $car_info=array(
                            "car_no"=>$car->car_no,
                            "car_brand_id"=> $car->car_brand_id,
                            "car_brand_name"=> $csi->brand_name,
                            "car_series_id"=> $car->car_series_id,
                            "car_series_name"=> $csi->series_name,
                            "car_model_id"=> $car->car_model_id,
                            "car_model_name"=> $csi->model_name,
                            "vin"=>$car->vin_code,
                            "mileage"=> $car->mileage,
                            "note"=> $car->note,
                        );
                    }
                }
            }
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("user_info"=>$user_array,"car_info"=>$car_info));
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "search_order", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);

    }


    /**
     * @Author:      lyt
     * @DateTime:  2017-05-16 18:16:04
     * @Description: 洗车查询用户
     */
    public  function search_user_car_wash(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                "phone"=>'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $id_arr=DB::select("select GROUP_CONCAT(DISTINCT user_id) as user_id from user_car_info where car_no like '%".Input::get("phone")."%'");
            if(!$id_arr[0]->user_id){
                $id_arr[0]->user_id=0;
            }
            $sql="SELECT
                        u.*, xj.balance xj_balance, xn.balance xn_balance,  gz.balance gz_balance,  gz.credit
                    FROM
                        `users` u
                    -- LEFT JOIN user_car_info uci on uci.user_id=u.id
                    LEFT JOIN ( SELECT  sum(balance) as balance ,user_id  FROM  user_account_details    WHERE       acount_type = 1) xj ON u.id = xj.user_id
                    LEFT JOIN ( SELECT  sum(balance) as balance ,user_id  FROM  user_account_details    WHERE       acount_type = 2) xn ON u.id = xn.user_id
                    LEFT JOIN ( SELECT  sum(balance) as balance ,sum(credit) as credit,user_id FROM user_account_details WHERE acount_type = 3) gz ON u.id = gz.user_id
                    where u.`status`=1 and (u.phone like '%".Input::get("phone")."%' or u.ID in(".$id_arr[0]->user_id.")  or u.real_name like '%".Input::get("phone")."%') ";

            // $user=Users::where("phone","like","%".Input::get("phone")."%")->where("status",1);

            if(Input::get("type")){
                $sql=$sql. ' and u.type='.Input::get("type");
            }
            $user=DB::select($sql." limit 15 ");
            $user_array=array();
            foreach ($user as $_user) {
                $user_array[]=array(
                    "id"=>$_user->id,
                    "name"=>$_user->real_name,
                    "phone"=>$_user->phone,
                    "type"=>$_user->type,
                    "id_card"=>$_user->id_card,
                    'account_balance'=>bcdiv(($_user->xj_balance==null?0:$_user->xj_balance)+($_user->xn_balance==null?0:$_user->xn_balance),100,2),
                    'credit_balance'=>bcdiv(($_user->gz_balance==null?0:$_user->gz_balance),100,2),
                    'credit'=>bcdiv(($_user->credit==null?0:$_user->credit),100,2),
                );
            }
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("count"=>sizeof($user_array),"user_info"=>$user_array));
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "search_user_car_wash", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);

    }


    /**
     * @Author:      lyt
     * @DateTime:  2017-05-22 17:54:33
     * @Description: 查询用户接口
     */
    public  function search_user_args(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }


            $sql="SELECT
                        u.*, xj.balance xj_balance, xn.balance xn_balance,  gz.balance gz_balance,  gz.credit
                    FROM
                        `users` u
                    -- LEFT JOIN user_car_info uci on uci.user_id=u.id
                    LEFT JOIN ( SELECT  sum(balance) as balance ,user_id  FROM  user_account_details    WHERE       acount_type = 1) xj ON u.id = xj.user_id
                    LEFT JOIN ( SELECT  sum(balance) as balance ,user_id  FROM  user_account_details    WHERE       acount_type = 2) xn ON u.id = xn.user_id
                    LEFT JOIN ( SELECT  sum(balance) as balance ,sum(credit) as credit,user_id FROM user_account_details WHERE acount_type = 3) gz ON u.id = gz.user_id
                    where  u.`status`=1 ";

            // $user=Users::where("phone","like","%".Input::get("phone")."%")->where("status",1);

            if(Input::get("phone")){
                $sql=$sql. " and  u.phone like '%".Input::get("phone")."%'";
            }
            if(Input::get("car_no")){
                $id_arr=DB::select("select GROUP_CONCAT(DISTINCT user_id)  as user_id from user_car_info where car_no like '%".Input::get("car_no")."%'");
                if(!$id_arr[0]->user_id){
                    $id_arr[0]->user_id=0;
                }
                $sql=$sql. " and  u.id in(".$id_arr[0]->user_id.") ";             
            }
            if(Input::get("type")){
                $sql=$sql. ' and u.type='.Input::get("type");
            }
            $user=DB::select($sql." limit 15 ");
            $user_array=array();
            foreach ($user as $_user) {
                $user_array[]=array(
                    "id"=>$_user->id,
                    "name"=>$_user->real_name,
                    "phone"=>$_user->phone,
                    "sex"=>$_user->sex,
                    "type"=>$_user->type,
                    'account_balance'=>bcdiv(($_user->xj_balance==null?0:$_user->xj_balance)+($_user->xn_balance==null?0:$_user->xn_balance),100,2),
                    'credit_balance'=>bcdiv(($_user->gz_balance==null?0:$_user->gz_balance),100,2),
                    'credit'=>bcdiv(($_user->credit==null?0:$_user->credit),100,2),
                );
            }
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("count"=>sizeof($user_array),"user_info"=>$user_array));
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "search_user_args", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);

    }

    /**
     * @Author:      lyt
     * @DateTime:  2017-07-31 12:34:48
     * @Description: 用于不包含特殊用户的额查询
     */
    public  function search_user_noargs(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }


            $sql="SELECT
                        u.*, xj.balance xj_balance, xn.balance xn_balance,  gz.balance gz_balance,  gz.credit
                    FROM
                        `users` u
                    -- LEFT JOIN user_car_info uci on uci.user_id=u.id
                    LEFT JOIN ( SELECT  sum(balance) as balance ,user_id  FROM  user_account_details    WHERE       acount_type = 1) xj ON u.id = xj.user_id
                    LEFT JOIN ( SELECT  sum(balance) as balance ,user_id  FROM  user_account_details    WHERE       acount_type = 2) xn ON u.id = xn.user_id
                    LEFT JOIN ( SELECT  sum(balance) as balance ,sum(credit) as credit,user_id FROM user_account_details WHERE acount_type = 3) gz ON u.id = gz.user_id
                    where  u.`status`=1 and u.id !=1509 and u.id !=1000000000 ";

            // $user=Users::where("phone","like","%".Input::get("phone")."%")->where("status",1);

            if(Input::get("phone")){
                $sql=$sql. " and  u.phone like '%".Input::get("phone")."%'";
            }
            if(Input::get("car_no")){
                $id_arr=DB::select("select GROUP_CONCAT(DISTINCT user_id)  as user_id from user_car_info where car_no like '%".Input::get("car_no")."%'");
                if(!$id_arr[0]->user_id){
                    $id_arr[0]->user_id=0;
                }
                $sql=$sql. " and  u.id in(".$id_arr[0]->user_id.") ";             
            }
            if(Input::get("type")){
                $sql=$sql. ' and u.type='.Input::get("type");
            }
            $user=DB::select($sql." limit 15 ");
            $user_array=array();
            foreach ($user as $_user) {
                $user_array[]=array(
                    "id"=>$_user->id,
                    "name"=>$_user->real_name,
                    "phone"=>$_user->phone,
                    "sex"=>$_user->sex,
                    "type"=>$_user->type,
                    'account_balance'=>bcdiv(($_user->xj_balance==null?0:$_user->xj_balance)+($_user->xn_balance==null?0:$_user->xn_balance),100,2),
                    'credit_balance'=>bcdiv(($_user->gz_balance==null?0:$_user->gz_balance),100,2),
                    'credit'=>bcdiv(($_user->credit==null?0:$_user->credit),100,2),
                );
            }
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("count"=>sizeof($user_array),"user_info"=>$user_array));
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "search_user_args", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);

    }

    // /**
    //  * @Author:      lyt
    //  * @DateTime:    2016-01-08 16:31:48
    //  * @Description: 搜索车辆信息
    //  */
    // public function search_car(){
    //     $validator = Validator::make(Input::all(),
    //         array(
    //             'token' => 'required',
    //         )
    //     );
    //     $response = array('code' => 0, 'msg' => 'ok');
    //     do{
    //         if($validator->fails()) {
    //             $response = Lang::get("scs_error.args_error_10000");
    //             $response["result"]=$validator->messages()->all();
    //             break;
    //         }
    //         $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
    //         if(is_null($sc_user)){
    //             break;
    //         }
    //         $orders=Orders::leftJoin("user_car_info","user_car_info.id","=","orders.user_car_id")->where("orders.shop_id",$sc_user->shop_id)->orderBy("orders.book_time",'desc');
    //         if(Input::get("order_id")){
    //             $orders=$orders->where("orders.order_id",Input::get("order_id"));
    //         }

    //         if(Input::get("phone")){
    //             $orders=$orders->where("orders.phone",Input::get("phone"));
    //         }
    //         $orders=$orders->select("")->get();
    //         $arr_order=array();
    //         foreach ($orders as $_order) {
    //             $arr_order[]=array(
    //                 "order_id"=>$_order->order_id,
    //                 "start_time"=>$_order->start_time,
    //                 "end_time"=>$_order->end_time,
    //                 "book_time"=>$_order->book_time,
    //                 "book_hour"=>$_order->book_hour,
    //                 "status"=>$_order->status
    //             );
    //         }
    //         $temp_arr=array(
    //             "car_no"=>$msc->car_no,
    //             "kilometre"=>"",
    //             "befor_kilometre"=>$number,
    //             "vin"=>"",
    //             "desc"=>"",
    //             "brand_name"=>$csi->brand_name,
    //             "series_name"=>$csi->series_name,
    //             "model_name"=>$csi->model_name,
    //             "model_id"=>$csi->id,
    //         );


    //         $response = array('code' => 0, 'msg' => 'ok', 'result' => array("count"=>sizeof($arr_order),"orders"=>$arr_order));
    //     }while(false);
    //     Log::info("info", array("system" => "scs" ,"event" => "search_order", 'input' =>Input::all() ,"output" => $response));
    //     return json_encode($response);
    // }
    /**
     * @Author:      zwh
     * @DateTime:    2016-1-28 15:16:42
     * @Description: 根据车型和车牌号获取订单
     */
    public  function search_orders(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                "car_model_id"=>'integer|required',
                "car_no"=>'required',
            )
            );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $orders=Orders::where("shop_id",$sc_user->shop_id)
                ->where('car_model_id',Input::get('car_model_id'))
                ->where('car_no',Input::get('car_no'))
                ->where('place',2)
                ->whereIn('status',Orders::$search_orders)
                ->orderBy("book_time",'desc')
                ->get();
            $arr_order=array();
            foreach ($orders as $_order) {
                $arr_order[]=array(
                    "order_id"=>$_order->order_id,
                    "start_time"=>$_order->start_time,
                    "end_time"=>$_order->end_time,
                    "book_time"=>$_order->book_time,
                    "book_hour"=>$_order->book_hour,
                    "order_type"=>$_order->order_type,
                    "status"=>$_order->status
                );
            }
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("count"=>count($orders),"orders"=>$arr_order));
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "search_orders", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);

    }

    /**
     * @Author:      lyt
     * @DateTime:    2016-05-13 15:23:29
     * @Description: 新下单流程 根据车牌号选择用户的信息  下单
     * @link http://api.anhui.com/v1/scs/search/search_carno?token=efc85ce01d0e523e5d4507fac1beb4f6&car_no=京A12345
     */
    public function search_carno(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                "car_no"=>'required',
            )
            );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $select_arr = [
                'user_car_info.id as user_car_id', 'user_car_info.car_model_id', 'user_car_info.vin_code', 
                'user_car_info.mileage', 'user_car_info.insurance', 'user_car_info.start_off_time', 'users.id as user_id', 
                'users.phone', 'users.real_name',  'users.sex', 'users.type', 'car_standard_info.brand_name_id as brand_id', 
                'car_standard_info.brand_name',  'car_standard_info.series_name_id as series_id', 'car_standard_info.series_name', 
                'car_standard_info.model_year', 'car_standard_info.model_name', 
                'users.experience', 'member_ordinary.name AS member_level_name', 'member_ordinary.dis AS member_dis',
            ];
            $uci=UserCarInfo::leftJoin("users","users.id","=","user_car_info.user_id")
                    ->leftJoin("anhui_data.car_standard_info","anhui_data.car_standard_info.id","=","user_car_info.car_model_id")
                    ->leftJoin('member_ordinary', 'users.member', '=', 'member_ordinary.id')
                    // ->leftJoin("orders","orders.user_id","=","users.id")
                    ->where("user_car_info.status",1)
                    ->where("users.status",1)
                    ->where("users.id","!=",1000000000)//过滤特殊用户
                    ->where("user_car_info.car_no",Input::get("car_no"))
                    // ->orderBy("orders.pay_time",'desc')
//                    ->select("user_car_info.id as user_car_id","user_car_info.car_model_id","user_car_info.vin_code",
//                        "user_car_info.mileage","user_car_info.insurance","user_car_info.start_off_time","users.id as user_id",
//                        "users.phone","users.real_name", "users.sex","users.type","car_standard_info.brand_name_id as brand_id",
//                        "car_standard_info.brand_name", "car_standard_info.series_name_id as series_id","car_standard_info.series_name",
//                        "car_standard_info.model_year","car_standard_info.model_name")
                    ->select($select_arr)
                    ->get();
            $finally_arr=array();
            foreach ($uci as $_uci) {                
                if($_uci->type==2){//如果是企业用户
                    $compnay=Companys::find($_uci->user_id);
                    $_uci->company_name=isset($compnay)?$compnay->name:"";
                    $ucd=UserCarDesc::find($_uci->user_car_id);
                    $_uci->card_no=isset($ucd) ? $ucd->card_no : "";
                    $_uci->user_car_phone=isset($ucd->phone) ? $ucd->phone : "";
                }else{
                    $_uci->company_name="";
                    $_uci->identification_number="";
                    $_uci->card_no="";
                }
                //查询用户的临时会员    start
                $mtu_member = MemberTemporaryUser::leftJoin("member_temporary","member_temporary.id","=","member_temporary_user.member_temporary_id")
                        ->where("member_temporary_user.user_id",$_uci->user_id)
                        ->where("member_temporary_user.end_time",">",Common::currentTimeString())
                        ->orderBy("member_temporary.dis","asc")
                        ->select("member_temporary.dis","member_temporary.name","member_temporary_user.created_at")
                        ->first();
                if($mtu_member){
                    $pt_dis = isset($_uci['member_dis']) ? $_uci['member_dis'] : 1;   //普通会员折扣
                    $ls_dis = isset($mtu_member->dis) ? $mtu_member->dis : 1;         //临时折扣
                    if($ls_dis < $pt_dis){
                        $_uci['experience'] = '';
                        $_uci['member_level_name'] = $mtu_member->name;
                        $_uci['member_dis'] = $ls_dis;
                    }
                }
                //查询用户的临时会员    end
                
                $order=Orders::where("user_id",$_uci->user_id)->max("created_at");
                $finally_arr[$order]=$_uci;
            }
            
            krsort($finally_arr);
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("count"=>count($finally_arr),"user_car_info"=>array_values($finally_arr)));
            // $response = array('code' => 0, 'msg' => 'ok', 'result' => array("count"=>count($finally_arr),"user_car_info"=>$finally_arr));
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "search_carno", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     * @Author:          zk
     * @DateTime:        18-5-2 下午3:00
     * @Description:     获取车型级别
     * @param string $token     用户token
     * @link http://api.anhui.com/v1/scs/search/get_car_model_level?token=811ad25cf2d0a0e2718f33ebc68b21bc
     */
    public function get_car_model_level(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user = $this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $list_info = WorkModelCoefficient::select('name')->get();
            
            $response = array('code' => 0, 'msg' => 'ok', 'result' => $list_info);
        }while(false);
        
        Log::info("info", array("system" => "scs" ,"event" => "get_car_model_level", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     * @Author:          zk
     * @DateTime:        18-5-2 下午4:00
     * @Description:     历史保养订单回访记录添加与更新
     * @param string $token     用户token
     * @param string $order_id  订单编号
     * @param int $type         回访类型(1:未回访;2:留存跟进;3:流失;)
     * @param string $remark    回访备注
     * @link http://api.anhui.com/v1/scs/search/history_maintain_visit?token=811ad25cf2d0a0e2718f33ebc68b21bc&type=1&order_id=14628742715391
     */
    public function history_maintain_visit(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'order_id' => 'required',
                'type' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user = $this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $admin_id = $sc_user->id;
            $now_time = date('Y-m-d H:i:s', time());
            
            $order_id = Input::get('order_id');
            $type = Input::get('type');
            $remark = Input::get('remark', '');     //备注信息
            $visit_info = OrderHistoryMaintainVisit::where('order_id', $order_id)->first();
            if($visit_info){     //更新回访记录
                DB::beginTransaction();
                try{
                    $visit_data['order_id'] = $order_id;
                    $visit_data['type'] = $type;
                    if($remark != ''){
                        $visit_data['remark'] = $remark;
                    }
                    $visit_data['updated_by'] = $admin_id;
                    $visit_data['updated_at'] = $now_time;
                    $visit_res = OrderHistoryMaintainVisit::where('order_id', $order_id)->update($visit_data);
                    
                    $update_data['visit_type'] = $type;     //回访类型(1:未回访;2:留存跟进;3:流失;)
                    $update_res = OrderHistoryMaintain::where('order_id', $order_id)->update($update_data);
                    if($visit_res && $update_res){
                        DB::commit();
                    }
                } catch (Exception $e){
                    DB::rollBack();
                    Log::error("error", array("system" => "scs" ,"event" => "history_maintain_visit", 'input' =>Input::all() ,"exception" => $e));
                    $response = Lang::get("scs_error.data_inventory_isrun_61022");
                    break;
                }
            } else {        //新增回访记录
                DB::beginTransaction();
                try{
                    $visit_data['order_id'] = $order_id;
                    $visit_data['type'] = $type;
                    if($remark != ''){
                        $visit_data['remark'] = $remark;
                    }
                    $visit_data['create_by'] = $admin_id;
                    $visit_data['created_at'] = $now_time;
                    $visit_data['updated_by'] = $admin_id;
                    $visit_data['updated_at'] = $now_time;
                    $visit_res = OrderHistoryMaintainVisit::insert($visit_data);
                    
                    $update_data['visit_type'] = $type;     //回访类型(1:未回访;2:留存跟进;3:流失;)
                    $update_res = OrderHistoryMaintain::where('order_id', $order_id)->update($update_data);
                    if($visit_res && $update_res){
                        DB::commit();
                    }
                } catch (Exception $e){
                    DB::rollBack();
                    Log::error("error", array("system" => "scs" ,"event" => "history_maintain_visit", 'input' =>Input::all() ,"exception" => $e));
                    $response = Lang::get("scs_error.data_inventory_isrun_61022");
                    break;
                }
            }
        }while(false);
        
        Log::info("info", array("system" => "scs" ,"event" => "history_maintain_visit", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     * @Author:          zk
     * @DateTime:        18-5-3 下午1:05
     * @Description:     根据保养订单号获取回访信息
     * @param string $token     用户token
     * @param string $order_id  订单编号
     * @link http://api.anhui.com/v1/scs/search/get_return_visit?token=2f5d458269a0d8fdc7be1d9dd9cc8740&order_id=14628742715391
     */
    public function get_return_visit(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'order_id' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user = $this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            
            $order_id = Input::get('order_id', '');
            $visit_info = OrderHistoryMaintainVisit::where('order_id', $order_id)->first();
            $response = array('code' => 0, 'msg' => 'ok', 'result' => $visit_info);
        }while(false);
        
        Log::info("info", array("system" => "scs" ,"event" => "get_return_visit", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /**
     * @Author:          zk
     * @DateTime:        18-5-3 上午11:25
     * @Description:     回保查询    [ 查看在店保养服务周期内未回保的车辆及信息 ]默认展示 (本门店、个人用户、全部车型级别、最近6个月、未回访、全部记录)
     * @param string $token         用户token
     * @param string $start_time    开始时间
     * @param string $end_time      截止时间
     * @param string $car_level     车型级别
     * @param int $type             回访类型(1:未回访;2:留存跟进;3:流失;)
     * @param int $page             页码 [ 默认为1 ]
     * @param int $page_size        每页数据条数 [ 默认为20 ]
     * @link http://api.anhui.com/v1/scs/search/search_history_maintain?token=2f5d458269a0d8fdc7be1d9dd9cc8740
     */
    public function search_history_maintain(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'page' => 'integer',
                'page_size' => 'integer',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $shop_id = $sc_user->shop_id;   //当前门店id
            $user_type = 1;                 //用户类型 1:个人用户; 2:企业;
            $num = 180;                     //默认天数
            
            $start_time = Input::get('start_time', '');
            $end_time = Input::get('end_time', '');
            $car_level = Input::get('car_level', '');
            $type = Input::get('type', '');
            $page = Input::get('page', 1);
            $page_size = Input::get('page_size', 20);
            if($start_time == '' && $end_time == ''){
                $start_time = date('Y-m-d', strtotime("-".$num." day"));
                $end_time = date('Y-m-d', time());
            }
            
            //获取 从截止时间到当前时间 有保养的车信息
            $base_list = DB::table('order_history_maintain')
                    ->leftJoin('users', 'order_history_maintain.user_id', '=', 'users.id')
                    ->where('order_history_maintain.shop_id', $shop_id)
                    ->where('users.type', $user_type)
                    ->where('order_history_maintain.created_time', '>', $end_time.' 23:59:59')
                    ->select('order_history_maintain.user_car_id', 'order_history_maintain.pay_time')
                    ->groupBy('order_history_maintain.user_car_id')
                    ->get();
            $base_arr = [];     //用户车辆id数组
            if($base_list){
                foreach ($base_list as $v) {
                    $base_arr[] = $v->user_car_id;
                }
            }
            
            $list_info = DB::table(DB::raw('(SELECT user_car_id, MAX(created_time) AS max_time FROM order_history_maintain GROUP BY user_car_id) AS order_history_maintain_dis'))
                    ->leftJoin('order_history_maintain', 'order_history_maintain.user_car_id', '=', 'order_history_maintain_dis.user_car_id')
                    ->whereRaw("order_history_maintain.created_time = order_history_maintain_dis.max_time")
                    ->leftJoin('order_history_maintain_visit', 'order_history_maintain.order_id', '=', 'order_history_maintain_visit.order_id')
                    ->leftJoin('orders', 'order_history_maintain.order_id', '=', 'orders.order_id')
                    ->leftJoin('users', 'order_history_maintain.user_id', '=', 'users.id')
                    ->leftJoin('user_car_info', 'order_history_maintain.user_car_id', '=', 'user_car_info.id')
                    ->leftJoin('anhui_data.car_standard_info', 'user_car_info.car_model_id', '=', 'car_standard_info.id')
                    ->where('order_history_maintain.created_time', '>', $start_time.' 00:00:00')
                    ->where('order_history_maintain.created_time', '<', $end_time.' 23:59:59')
                    ->where('order_history_maintain.shop_id', $shop_id)
                    ->where('users.type', $user_type);
            if(!empty($basic_arr)){
                $list_info->whereNotIn('order_history_maintain.user_car_id', $basic_arr);
            }
            if($type != ''){
                $list_info->where('order_history_maintain.visit_type', $type);
            }
            if($car_level != ''){
                $list_info->where('car_standard_info.model_level', 'like', '%'.$car_level.'%');
            }
            $list_info->select('order_history_maintain.order_id','order_history_maintain.name as s_name',
                    'order_history_maintain.phone as s_phone','order_history_maintain.user_car_id','order_history_maintain.car_no',
                    'order_history_maintain.created_time','order_history_maintain.pay_time','order_history_maintain.car_brand_id',
                    'order_history_maintain.car_brand_name','order_history_maintain.car_series_id','order_history_maintain.car_series_name',
                    'order_history_maintain.car_model_id','order_history_maintain.car_model_name','order_history_maintain.shop_id',
                    'order_history_maintain.product_type','users.id AS user_id','users.phone','users.real_name','users.type','orders.mileage',
                    'order_history_maintain.visit_type','order_history_maintain_visit.remark','car_standard_info.model_level');
            $count = $list_info->count();
            $list_info = $list_info->skip($page_size*($page-1))->take($page_size)->get();
            
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array('count' => $count, 'list' => $list_info));
        }while(false);
        
        Log::info("info", array("system" => "scs" ,"event" => "search_history_maintain", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
}